#include "stm32f4xx.h"
#include "Bsp.h"

void TIM3_Init_500ms(void)
{
    TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
    NVIC_InitTypeDef NVIC_InitStructure;

    // 1. 打开时钟
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);

    // 2. 设置 NVIC 中断优先级
    NVIC_InitStructure.NVIC_IRQChannel = TIM3_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority = 1;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);

    // 3. 定时器时基配置
    // 计算：
    // 假设定时器时钟 = APB1 * 2 = 164MHz / 2 = 82MHz
    // 如果 Prescaler = 8199，那么定时器频率为 10KHz（每个计数 = 0.1ms）
    // 要定时500ms = 5000 × 0.1ms -> Period = 4999

    TIM_TimeBaseStructure.TIM_Period = 4999;                     // 自动重装值 (ARR)
    TIM_TimeBaseStructure.TIM_Prescaler = 8199;                  // 预分频系数 (PSC)
    TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;      // 时钟分频
    TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;  // 向上计数模式
    TIM_TimeBaseInit(TIM3, &TIM_TimeBaseStructure);

    // 4. 清除更新中断标志位
    TIM_ClearITPendingBit(TIM3, TIM_IT_Update);

    // 5. 使能更新中断
    TIM_ITConfig(TIM3, TIM_IT_Update, ENABLE);

    // 6. 启动定时器
    TIM_Cmd(TIM3, ENABLE);
}
